package com.sc.highspeed.tools;

import com.sc.highspeed.constant.Constant;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;

/**
 * Created by Admin on 2017/12/23.
 */
public class PictureUpload {
    public static String uploadPicture(CommonsMultipartFile file) throws Exception {
        long maxSize = 1024 * 1024 * 100;
        String allowExts = "jpg,png,gif";
        String basePath = Constant.PICPATH;

        String iconName = file.getOriginalFilename();
        String fileExt = iconName.substring(iconName.lastIndexOf(".") + 1).toLowerCase();
        if (file.getSize() > maxSize) {
            throw new Exception("文件大小超标！");
        } else if (!Arrays.asList(allowExts.split(",")).contains(fileExt)) {
            throw new Exception("文件格式不符合要求！");
        }

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = format.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(basePath, newFileName));
        } catch (IOException e) {
            throw new Exception("文件写入失败！");
        }

        return "/file/picture/" + newFileName;

    }
}
